import * as types from './mutation-types';
import { playMode } from '../common/js/config';
import { random } from '../common/js/dom';
import { findSong } from '../common/js/song';

export default {
  selectPlay({ commit }, { index, list }) {
    commit(types.SET_CURRENT_INDEX, index);
    commit(types.SET_PLAYING_STATE, true);
    if (list) {
      commit(types.SET_PLAYLIST, list);
      commit(types.SET_FULL_SCREEN, true);
    }
  },
  randomPlay({ commit }, { list }) {
    commit(types.SET_CURRENT_INDEX, random(list.length));
    commit(types.SET_PLAYING_STATE, true);
    commit(types.SET_PLAYLIST, list);
    commit(types.SET_PLAY_MODE, playMode.random);
  },
  clearPlayList({ commit }) {
    commit(types.SET_PLAYLIST, []);
    commit(types.SET_CURRENT_INDEX, -1);
    commit(types.SET_PLAYING_STATE, false);
  },
  deleteSong({ commit, state }, song) {
      let currentIndex = state.currentIndex;
      const isPlaying = state.playing;
      const playlist = state.playlist.slice(0);
      const ifIndex = findSong(playlist, song);
      if (ifIndex < currentIndex) {
          // 被删歌曲在当前播放歌曲之前
          currentIndex -= 1;
      }
      playlist.splice(ifIndex, 1);
      if (playlist.length === 0) {
          // 删除之后列表为空
          commit(types.SET_PLAYING_STATE, false);
          commit(types.SET_CURRENT_INDEX, -1);
      } else {
          // 如果删的是正在播放的且是第一首歌
          if (currentIndex === -1) {
              currentIndex = 0;
          }
          // 播放模式
          if (state.mode === playMode.random) {
              currentIndex = random(playlist.length);
          }
          commit(types.SET_CURRENT_INDEX, currentIndex);
          if (!isPlaying) {
              commit(types.SET_PLAYING_STATE, true);
          }
      }
      commit(types.SET_PLAYLIST, playlist);
  },
  insertSong({ commit, state }, song) {
    const playlist = state.playlist.slice(0);
    const ifIndex = findSong(playlist, song);
    if (ifIndex > -1) {
      // 列表中存在当前搜索歌曲
      commit(types.SET_CURRENT_INDEX, ifIndex);
    } else {
      // 不存在,插入list首位
      playlist.unshift(song);
      commit(types.SET_PLAYLIST, playlist);
      commit(types.SET_CURRENT_INDEX, 0);
    }
    commit(types.SET_PLAYING_STATE, true);
    // commit(types.SET_FULL_SCREEN, true);
  },
  savePlayHistory({ commit }, list) {
    commit(types.SET_PLAY_HISTORY, list);
  },
};

